<?php
!defined('P_W') && exit('Forbidden');
class PW_House_PushDataDB extends BaseDB {
	var $_tableName = "pw_house_pushdata";
	
	function get($id) {
		$temp = $this->_db->get_one('SELECT * FROM '.$this->_tableName.' WHERE id='.pwEscape($id));
		$temp = $this->_unserializeData($temp);
		return $temp;
	}
	
	function getByModel($hid,$model,$start,$preg) {
		$temp = array();
		$rs = $this->_db->query('SELECT * FROM '.$this->_tableName.' WHERE hid='.pwEscape($hid).' AND model='.pwEscape($model).' ORDER BY iffailure , offset '.pwLimit($start,$preg));
		while ($rt = $this->_db->fetch_array($rs)) {
			$rt = $this->_unserializeData($rt);
			$temp[$rt['id']] = $rt; 
		}
		return $temp;
	}
	function getOpenPushs($hid,$model,$num=10) {
		$temp = array();
		$rs = $this->_db->query('SELECT * FROM '.$this->_tableName.' WHERE hid='.pwEscape($hid).' AND model='.pwEscape($model).' AND iffailure=0 ORDER BY iffailure , offset '.pwLimit(0,$num));
		while ($rt = $this->_db->fetch_array($rs)) {
			$rt = $this->_unserializeData($rt);
			$temp[$rt['id']] = $rt; 
		}
		return $temp;
		
	}
	
	function insert($array) {
		$array	= $this->_checkData($array);
		if (!$array) return null;
		$this->_db->update('INSERT INTO '.$this->_tableName.' SET '.pwSqlSingle($array,false));
		return $this->_db->insert_id();
	}
	function setIffailureStates($array,$state) {
		$state = (int) $state;
		if (!$array || !is_array($array)) return null;
		//print_r('UPDATE '.$this->_tableName.' SET iffailure ='.pwEscape($state).' WHERE id IN ('.pwImplode($array).')');exit;
		$this->_db->update('UPDATE '.$this->_tableName.' SET iffailure ='.pwEscape($state).' WHERE id IN ('.pwImplode($array).')');
	}

	function update($id,$array) {
		$array	= $this->_checkData($array);
		if (!$array) return null;
		$this->_db->update('UPDATE '.$this->_tableName.' SET '.pwSqlSingle($array,false).' WHERE id='.pwEscape($id));
	}
	function delete($id) {
		$this->_db->update('DELETE FROM '.$this->_tableName.' WHERE id='.pwEscape($id));
	}

	function getStruct() {
		return array('id','hid','model','title','titlecss','url','image','data','offset','author','pushtime','iffailure');
	}
	function countByModel($hid,$model) {
		return $this->_db->get_value('SELECT COUNT(*) AS count FROM '.$this->_tableName.' WHERE hid='.pwEscape($hid).' AND model='.pwEscape($model));
	}

	function _checkData($data) {
		if (!is_array($data) || !count($data)) return null;	
		$data = $this->_checkAllowField($data,$this->getStruct());
		$data = $this->_serializeData($data);
		
		return $data;
	}
	
	function _serializeData($data) {
		$data['data'] = $data['data'] ? serialize($data['data']) : '';
		$data['titlecss'] = serialize($data['titlecss']);
		return $data;
	}
	function _unserializeData($data) {
		$data['data'] = $data['data'] ? unserialize($data['data']) : '';
		$data['titlecss'] = unserialize($data['titlecss']);
		return $data;
	}


}
?>